<?php

namespace EthanZ\LaravelExt\Utils\Tools;

use EthanZ\LaravelExt\Constants\CommonSetting;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;

/**
 * 时间工具类
 */
class TimeTools
{


    /**
     * 开始时间结束时间整理
     *
     * @param int $startTime 开始时间.
     * @param int $endTime   结束时间.
     *
     * @return array
     */
    public static function betweenTime(int $startTime, int $endTime): array
    {
        $betweenTime = [];
        if ($startTime || $endTime) {
            $startTime = $startTime ?: 0;
            $endTime   = $endTime ?: 9999999999;
            // 大小判断.
            if ($startTime <= $endTime) {
                $betweenTime = [$startTime, $endTime];
            } else {
                $betweenTime = [$endTime, $startTime];
            }
        }

        return $betweenTime;
    }


    /**
     * 季度格式化
     *
     * @param int $time 时间
     *
     * @return string
     */
    public static function quarterFormat(int $time): string
    {
        $year    = date('Y', $time);
        $quarter = ceil(date('n', $time) / 3);

        return Str::replaceArray('?', [$year, $quarter], CommonSetting::$dateFormat['quarter']);
    }


    /**
     * 获取两时间区间的所有时间
     *
     * @param int    $startTime 开始时间
     * @param int    $endTime   结束时间
     * @param string $type      类型
     *
     * @return array
     */
    public static function dateGroup(int $startTime, int $endTime, string $type): array
    {
        $res           = [];
        $startFunction = 'startOf' . Str::title($type);
        $endFunction   = 'endOf' . Str::title($type);
        $format        = CommonSetting::$dateFormat[$type];
        while ($startTime < $endTime) {
            $carbon        = Carbon::createFromTimestamp($startTime);
            $thisStartTime = $carbon->$startFunction()->timestamp;
            $thisEndTime   = $carbon->$endFunction()->timestamp;
            $res[]         = [
                'name'  => $type === 'quarter'
                    ? self::quarterFormat($thisStartTime)
                    : date($format, $thisStartTime),
                'start' => $thisStartTime,
                'end'   => $thisEndTime,
            ];
            $startTime     = (int)$thisEndTime + 1;
        }

        return $res;
    }
}
